export function formatFileSize(fileNumber: number | string) {
  const value =
    typeof fileNumber === 'string' ? Number(fileNumber) : fileNumber;
  const toFixed = (val: number) => val.toFixed(2);
  if (value < 1024) {
    return `${value}B`;
  } else if (value < 1048576) {
    return `${toFixed(value / 1024)}K`;
  } else if (value < 1073741824) {
    return `${toFixed(value / 1048576)}M`;
  } else if (value < 1099511627776) {
    return `${toFixed(value / 1073741824)}G`;
  } else if (value < 1125899906842624) {
    return `${toFixed(value / 1099511627776)}T`;
  }
}

export function formatDateTime(
  value: string | number | Date,
  needTime?: boolean
) {
  if (!!value) {
    const date = new Date(value);
    const datestr = date.getDate() > 9 ? date.getDate() : `0${date.getDate()}`;
    const minutesStr =
      date.getMinutes() > 9 ? date.getMinutes() : `0${date.getMinutes()}`;
    const secondsStr =
      date.getSeconds() > 9 ? date.getSeconds() : `0${date.getSeconds()}`;
    let str = `${date.getFullYear()}-${date.getMonth() + 1}-${datestr}`;
    if (needTime || needTime === undefined) {
      str += ` ${date.getHours()}:${minutesStr}:${secondsStr}`;
    }
    return str;
  }
  return '';
}

export function formatCentToYuan(cent: number) {
  let num = cent;
  num = cent * 0.01;
  let numStr = num + '';
  const reg =
    numStr.indexOf('.') > -1
      ? /(\d{1,3})(?=(?:\d{3})+\.)/g
      : /(\d{1,3})(?=(?:\d{3})+$)/g;
  numStr = numStr.replace(reg, '$1');
  numStr = toDecimal2(numStr);
  return numStr;
}

export function formatInputNumberToYuan(cent: number) {
  let num = cent;
  num = cent * 1;
  let numStr = num + '';
  const reg =
    numStr.indexOf('.') > -1
      ? /(\d{1,3})(?=(?:\d{3})+\.)/g
      : /(\d{1,3})(?=(?:\d{3})+$)/g;
  numStr = numStr.replace(reg, '$1');
  numStr = toDecimal2(numStr);
  return numStr;
}

export function isMoney(value: string) {
  const mny = /^[0-9]*(\.[0-9]{1,2})?$/;
  return mny.test(value);
}

export const toDecimal2 = (x: string) => {
  let f = parseFloat(x);
  if (isNaN(f)) {
    return '';
  }
  f = Math.round(+x * 100) / 100;
  let s = f.toString();
  let rs = s.indexOf('.');
  if (rs < 0) {
    rs = s.length;
    s += '.';
  }
  while (s.length <= rs + 2) {
    s += '0';
  }
  return s;
};
